﻿using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using Gavel.Common.Component.Extension;

namespace Gavel.Common.Component.Controls;

/// <summary>
/// 自定义窗口
/// </summary>
public class CustomWindow : Window
{
    /// <summary>
    /// 最小化按钮名称
    /// </summary>
    public const string Minimize = "Minimize";

    /// <summary>
    /// 最大化按钮名称
    /// </summary>
    public const string Maximize = "Maximize";

    /// <summary>
    /// 还原按钮名称
    /// </summary>
    public const string Restore = "Restore";

    /// <summary>
    /// 退出按钮名称
    /// </summary>
    public const string Exit = "Exit";

    /// <summary>
    /// 静态构造
    /// </summary>
    static CustomWindow() => DefaultStyleKeyProperty.OverrideDefaultStyle<CustomWindow>();

    /// <summary>
    /// 默认构造
    /// </summary>
    protected CustomWindow()
    {
        // 修复WindowChrome导致的窗口大小错误
        SizeToContent content = SizeToContent.Manual;
        Loaded += (_, _) => content = SizeToContent;
        ContentRendered += (_, _) =>
        {
            SizeToContent = SizeToContent.Manual;
            Width = ActualWidth;
            Height = ActualHeight;
            SizeToContent = content;
        };

        StateChanged += (_, _) =>
        {
            if (ResizeMode is not (ResizeMode.CanMinimize or ResizeMode.NoResize))
            {
                return;
            }

            if (WindowState == WindowState.Maximized)
            {
                WindowState = WindowState.Normal;
            }
        };
    }

    /// <summary>
    /// 重写模板应用方法绑定按钮事件
    /// </summary>
    public override void OnApplyTemplate()
    {
        base.OnApplyTemplate();
        (GetTemplateChild(Minimize) as Button)?.AttachButtonClickEvent((_, _) => SystemCommands.MinimizeWindow(this));
        (GetTemplateChild(Maximize) as Button)?.AttachButtonClickEvent((_, _) => SystemCommands.MaximizeWindow(this));
        (GetTemplateChild(Restore) as Button)?.AttachButtonClickEvent((_, _) => SystemCommands.RestoreWindow(this));
        (GetTemplateChild(Exit) as Button)?.AttachButtonClickEvent((_, _) => SystemCommands.CloseWindow(this));
    }

    /// <summary>
    /// 重写初始化完成方法
    /// 设置默认属性
    /// </summary>
    /// <param name="e">事件参数</param>
    protected override void OnInitialized(EventArgs e)
    {
        base.OnInitialized(e);
        WindowStartupLocation = WindowStartupLocation.CenterScreen;
        AllowsTransparency = false;
        if (WindowStyle == WindowStyle.None)
        {
            WindowStyle = WindowStyle.SingleBorderWindow;
        }
    }
}